/*
 * @FileName: app_mppt.c
 * @Author: GreyQiu qiushaogui@aikosolar.com
 * @Date: 2023-08-08 17:15:11
 * @LastEditors: GreyQiu qiushaogui@aikosolar.com
 * @LastEditTime: 2023-09-14 11:30:47
 * @Description: 
 * 
 * Copyright (c) 2023, All Rights Reserved. 
 */

#include "mppt.h"
#include "app_mppt.h"
#include <string.h>
#include "app_analog.h"
#include "loop.h"

// mppt数组，参数直接在数组中初始化
mppt_t mppt[BOOST_NUM] =
{
    // mppt1
    {.id = 0, .state = 0, .loop = &(controller[BOOST_ID_1]), .out = 54.0f, .outMax = 54.0f, .outMin = 19.0f, .pwr_pre = 0,
    .step = 0.8f, .stepMax = 0.8f, .stepMin = 0.4f, .stepGrad = 0.1f, .vin_addr = &(analog_tbl[BOOST_ID_1][ANALOG_ID_VIN].real_flt), .iin_addr = &(analog_tbl[BOOST_ID_1][ANALOG_ID_IIN].real_flt)},

    // mppt2
    {.id = 1, .state = 0, .loop = &(controller[BOOST_ID_2]), .out = 54.0f, .outMax = 54.0f, .outMin = 19.0f, .pwr_pre = 0,
    .step = 0.8f, .stepMax = 0.8f, .stepMin = 0.4f, .stepGrad = 0.1f, .vin_addr = &(analog_tbl[BOOST_ID_2][ANALOG_ID_VIN].real_flt), .iin_addr = &(analog_tbl[BOOST_ID_2][ANALOG_ID_IIN].real_flt)}
};

void app_mppt_run(void)
{
    for (uint16_t id = 0; id < BOOST_NUM; id++) {
        mppt_handle(&mppt[id]);
    }
}

void app_mppt_enable(uint16_t mppt_id)
{
    mppt[mppt_id].state = MPPT_STATE_TRACK;
}

void app_mppt_disable(uint16_t mppt_id)
{
    mppt[mppt_id].state = MPPT_STATE_DISABLE;
}

void app_mppt_init(uint16_t mppt_id, float Voc, float ref)
{
    mppt[mppt_id].dir[0] = 1;
    mppt[mppt_id].voc = Voc;
    mppt[mppt_id].outMax = Voc;
    mppt[mppt_id].out = ref;
    (mppt[mppt_id].loop->vin.ref) = mppt[mppt_id].out;
    mppt[mppt_id].cnt1 = 0;
    mppt[mppt_id].cnt2 = 0;
    mppt[mppt_id].cnt3 = 0;
    mppt[mppt_id].div = MPPT_PERIOD / 1;
}

void app_mppt_restart(uint16_t mppt_id)
{
    mppt[mppt_id].dir[0] = 1;
    mppt[mppt_id].out = mppt[mppt_id].voc * 0.95f;
    (mppt[mppt_id].loop->vin.ref) = mppt[mppt_id].out;
}

float app_mppt_get_ref(uint8_t mppt_id)
{
    return mppt[mppt_id].out;
}

uint8_t app_mppt_get_state(uint8_t mppt_id)
{
    return mppt[mppt_id].state;
}
